import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { ArrowLeft, Trophy, Calendar, DollarSign, MapPin, Users, Building, Globe, Tv, BarChart3, Clock, Database, Gamepad2, Eye, RefreshCw, Play, Pause, CheckCircle, Award } from "lucide-react"
import { LeagueDetail, LeagueSearchResult, LeagueMatch } from '@/types/dota'
import { useLeagueData } from '@/hooks/useLeagueData'
import LeaguePlayerRanking from './LeaguePlayerRanking'

interface LeagueInfoProps {
  leagueId: number
  onBack: () => void
  onViewMatches: (leagueId: number) => void
  onViewRankings?: (leagueId: number, leagueName: string) => void
  onDataLoaded?: (leagueId: number, data: { matches: LeagueMatch[], detail: LeagueDetail }) => void // 新增：数据加载回调
}

function LeagueInfo({ leagueId, onBack, onViewMatches, onViewRankings, onDataLoaded }: LeagueInfoProps) {
  const {
    leagueDetail,
    leagueMatches,
    loading,
    error,
    loadLeagueDetail,
    hasAnyData,
    enableAutoUpdate,
    disableAutoUpdate,
    checkForUpdates,
    lastUpdateCheck
  } = useLeagueData(leagueId)

  const [autoUpdateEnabled, setAutoUpdateEnabled] = useState(false)
  const [isCheckingUpdates, setIsCheckingUpdates] = useState(false)

  useEffect(() => {
    // 如果没有缓存数据，则加载联赛详情
    if (!leagueDetail) {
      loadLeagueDetail()
    }
  }, [leagueId, leagueDetail, loadLeagueDetail])

  // 当数据加载完成时，通知父组件
  useEffect(() => {
    if (leagueDetail && leagueMatches.length > 0 && onDataLoaded) {
      onDataLoaded(leagueId, {
        matches: leagueMatches,
        detail: leagueDetail
      })
    }
  }, [leagueDetail, leagueMatches, leagueId]) // 移除onDataLoaded依赖

  // 手动检查更新
  const handleCheckUpdates = async () => {
    setIsCheckingUpdates(true)
    try {
      await checkForUpdates()
    } finally {
      setIsCheckingUpdates(false)
    }
  }

  // 切换自动更新
  const handleToggleAutoUpdate = () => {
    if (autoUpdateEnabled) {
      disableAutoUpdate()
      setAutoUpdateEnabled(false)
    } else {
      enableAutoUpdate(5 * 60 * 1000) // 5分钟间隔
      setAutoUpdateEnabled(true)
    }
  }

  // 格式化最后更新检查时间
  const formatLastUpdateCheck = (timestamp?: number) => {
    if (!timestamp) return '从未检查'
    const now = Date.now()
    const diff = now - timestamp
    const minutes = Math.floor(diff / (1000 * 60))
    
    if (minutes < 1) return '刚刚检查'
    if (minutes < 60) return `${minutes}分钟前`
    const hours = Math.floor(minutes / 60)
    if (hours < 24) return `${hours}小时前`
    const days = Math.floor(hours / 24)
    return `${days}天前`
  }

  const formatDate = (timestamp?: number) => {
    if (!timestamp) return '未知'
    return new Date(timestamp * 1000).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    })
  }

  const formatPrizePool = (amount?: number) => {
    if (!amount) return '未知'
    return `$${amount.toLocaleString()}`
  }

  const getTierColor = (tier: string) => {
    switch (tier.toLowerCase()) {
      case 'premium': return 'bg-yellow-500'
      case 'professional': return 'bg-blue-500'
      case 'amateur': return 'bg-green-500'
      default: return 'bg-gray-500'
    }
  }

  if (loading.detail) {
    return (
      <div className="container mx-auto p-6">
        <div className="flex items-center gap-4 mb-6">
          <Button variant="outline" onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
        </div>
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-gray-600">正在加载联赛详情...</p>
          </div>
        </div>
      </div>
    )
  }

  if (error.detail) {
    return (
      <div className="container mx-auto p-6">
        <div className="flex items-center gap-4 mb-6">
          <Button variant="outline" onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
        </div>
        <Card className="border-red-200 bg-red-50">
          <CardContent className="p-6">
            <div className="text-center">
              <div className="text-red-600 mb-2">加载失败</div>
              <p className="text-gray-600 mb-4">{error.detail}</p>
              <Button onClick={loadLeagueDetail} variant="outline">
                重试
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  if (!leagueDetail) {
    return (
      <div className="container mx-auto p-6">
        <div className="flex items-center gap-4 mb-6">
          <Button variant="outline" onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
        </div>
        <div className="text-center py-12">
          <p className="text-gray-600">未找到联赛信息</p>
        </div>
      </div>
    )
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* 头部导航和控制 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="outline" onClick={onBack}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
        </div>
        
        {/* 增量更新控制面板 */}
        <div className="flex items-center gap-2">
          <div className="text-sm text-gray-500">
            最后检查: {formatLastUpdateCheck(lastUpdateCheck)}
          </div>
          
          <Button
            variant="outline"
            size="sm"
            onClick={handleCheckUpdates}
            disabled={isCheckingUpdates}
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${isCheckingUpdates ? 'animate-spin' : ''}`} />
            {isCheckingUpdates ? '检查中...' : '检查更新'}
          </Button>
          
          <Button
            variant={autoUpdateEnabled ? "default" : "outline"}
            size="sm"
            onClick={handleToggleAutoUpdate}
          >
            {autoUpdateEnabled ? (
              <>
                <Pause className="w-4 h-4 mr-2" />
                停止自动更新
              </>
            ) : (
              <>
                <Play className="w-4 h-4 mr-2" />
                启用自动更新
              </>
            )}
          </Button>
          
          {autoUpdateEnabled && (
            <Badge variant="secondary" className="text-xs">
              <CheckCircle className="w-3 h-3 mr-1" />
              自动更新中
            </Badge>
          )}
        </div>
      </div>

      {/* 联赛基本信息 */}
      <Card>
        <CardHeader>
          <div className="flex items-start justify-between">
            <div>
              <CardTitle className="text-2xl font-bold flex items-center gap-3">
                <Trophy className="w-8 h-8 text-yellow-500" />
                {leagueDetail.name}
              </CardTitle>
              <CardDescription className="mt-2 text-base">
                {leagueDetail.description || '暂无描述'}
              </CardDescription>
            </div>
            <div className="flex flex-col gap-2">
              <Badge className={getTierColor(leagueDetail.tier || 'unknown')}>
                {leagueDetail.tier || '未知等级'}
              </Badge>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {/* 时间信息 */}
            <div className="space-y-4">
              <h3 className="font-semibold text-lg flex items-center gap-2">
                <Calendar className="w-5 h-5" />
                时间信息
              </h3>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-gray-600">开始时间:</span>
                  <span>{formatDate(leagueDetail.start_time)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">结束时间:</span>
                  <span>{formatDate(leagueDetail.end_time)}</span>
                </div>
              </div>
            </div>

            {/* 奖金信息 */}
            <div className="space-y-4">
              <h3 className="font-semibold text-lg flex items-center gap-2">
                <DollarSign className="w-5 h-5" />
                奖金信息
              </h3>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-gray-600">奖金池:</span>
                  <span className="font-semibold text-green-600">
                    {formatPrizePool(leagueDetail.prize_pool)}
                  </span>
                </div>
              </div>
            </div>

            {/* 地区信息 */}
            <div className="space-y-4">
              <h3 className="font-semibold text-lg flex items-center gap-2">
                <MapPin className="w-5 h-5" />
                地区信息
              </h3>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-gray-600">地区:</span>
                  <span>{leagueDetail.region || '全球'}</span>
                </div>
              </div>
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="mt-6 pt-6 border-t flex gap-4">
            <Button onClick={() => onViewMatches(leagueId)} className="flex-1">
              <Eye className="w-4 h-4 mr-2" />
              查看比赛
            </Button>
            {onViewRankings && (
              <Button 
                onClick={() => onViewRankings(leagueId, leagueDetail?.name || '未知联赛')} 
                variant="outline"
                disabled={loading.detail || loading.matches || !leagueDetail?.stats?.matchCount}
                className="flex-1"
              >
                <Award className="w-4 h-4 mr-2" />
                联赛排行榜
              </Button>
            )}
            <Button variant="outline" onClick={loadLeagueDetail}>
              <RefreshCw className="w-4 h-4 mr-2" />
              刷新数据
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 联赛统计信息 */}
      {(leagueDetail.stats?.teamCount || leagueDetail.stats?.matchCount || leagueDetail.prize_pool) && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <BarChart3 className="w-5 h-5" />
              联赛统计
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {leagueDetail.stats?.teamCount && (
                <div className="text-center p-4 bg-blue-50 rounded-lg">
                  <Users className="w-8 h-8 text-blue-600 mx-auto mb-2" />
                  <div className="text-2xl font-bold text-blue-600">{leagueDetail.stats.teamCount}</div>
                  <div className="text-sm text-gray-600">参赛队伍</div>
                </div>
              )}
              
              {leagueDetail.stats?.matchCount && (
                <div className="text-center p-4 bg-green-50 rounded-lg">
                  <Gamepad2 className="w-8 h-8 text-green-600 mx-auto mb-2" />
                  <div className="text-2xl font-bold text-green-600">{leagueDetail.stats.matchCount}</div>
                  <div className="text-sm text-gray-600">总比赛数</div>
                </div>
              )}
              
              {leagueDetail.prize_pool && (
                <div className="text-center p-4 bg-yellow-50 rounded-lg">
                  <Trophy className="w-8 h-8 text-yellow-600 mx-auto mb-2" />
                  <div className="text-2xl font-bold text-yellow-600">
                    {formatPrizePool(leagueDetail.prize_pool)}
                  </div>
                  <div className="text-sm text-gray-600">总奖金池</div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 组织者信息 */}
      {leagueDetail.organizer && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Building className="w-5 h-5" />
              组织信息
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {leagueDetail.organizer && (
                <div>
                  <h4 className="font-semibold mb-2">主办方</h4>
                  <p className="text-gray-600">{leagueDetail.organizer}</p>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 直播和媒体信息 */}
      {leagueDetail.url && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Tv className="w-5 h-5" />
              媒体信息
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-4">
              {leagueDetail.url && (
                <Button variant="outline" asChild>
                  <a href={leagueDetail.url} target="_blank" rel="noopener noreferrer">
                    <Globe className="w-4 h-4 mr-2" />
                    官方链接
                  </a>
                </Button>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 联赛排名 */}
      <LeaguePlayerRanking leagueId={leagueId} />
    </div>
  )
}

export default LeagueInfo